﻿using Microsoft.Windows.Controls;
using System.Windows;


namespace HobSoft.SoccerBet2014.Common.Wpf.Behavior
{
    public class DataGridContextHelper
    {
        public static void Initialize()
        {

        }

        static DataGridContextHelper()
        {
            DependencyProperty dp = FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridColumn));
            FrameworkElement.DataContextProperty.OverrideMetadata(typeof(DataGrid),
            new FrameworkPropertyMetadata
               (null, FrameworkPropertyMetadataOptions.Inherits,
               new PropertyChangedCallback(OnDataContextChanged)));
        }

        public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataGrid grid = d as DataGrid;
            if (!grid.IsInitialized)
            {
                grid.Initialized += grid_Initialized;
                grid.Tag = e.NewValue;
            }
            if (grid != null)
            {
                foreach (DataGridColumn col in grid.Columns)
                {
                    col.SetValue(FrameworkElement.DataContextProperty, e.NewValue);
                }
            }
        }

        static void grid_Initialized(object sender, System.EventArgs e)
        {
            DataGrid grid = sender as DataGrid;
            foreach (DataGridColumn col in grid.Columns)
            {
                col.SetValue(FrameworkElement.DataContextProperty, grid.DataContext);
            }
        }
    }
}
